﻿using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Console = Colorful.Console;
using Utils;

namespace Client
{
    class Program
    {
        //全局IP、Port
        static string IP = "127.0.0.1";
        static ushort Port = 23333;

        //将IP地址写入配置文件
        static void GetIPUser()
        {
            Console.Write("Please enter Server IP: ");
            Config.WritePrivateProfileString("Client", "IP", Console.ReadLine(), @".\config.ini");
            Console.Write("Please enter Server Port: ");
            Config.WritePrivateProfileString("Client", "Port", Console.ReadLine(), @".\config.ini");
        }
        //从配置文件读取IP地址
        static void GetIPFile()
        {
            IP = Config.GetPrivateProfileString("Client", "IP", "127.0.0.1", @".\config.ini");
            Port = ushort.Parse(Config.GetPrivateProfileString("Client", "Port", "23333", @".\config.ini"));
        }

        //获取本机公网IP地址
        static string GetIP()
        {
            string ip;
            try
            {
                WebRequest wr = WebRequest.Create("http://ip.gs/ip");
                Stream s = wr.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(s, Encoding.Default);
                ip = sr.ReadToEnd(); //读取网站的数据
                ip = ip.Replace("\n", "");
                sr.Close();
                s.Close();
            }
            catch
            {
                return "-1";
            }
            return ip;
        }
        static void WriteLog(string ip)
        {
            Console.Write("[");
            Console.Write(DateTime.Now.ToLongTimeString(), Color.FromArgb(0, 255, 0));
            Console.Write("] ");
            Console.Write(ip);
            Console.WriteLine("   success", Color.FromArgb(0, 255, 0));
        }

        //将地址发送到全局中的IP Port
        static void SendIP()
        {
            TcpClient tcpClient = new TcpClient();
            try { tcpClient.Connect(IPAddress.Parse(IP), Port); }
            catch
            {
                Console.WriteLine("Can't send IP to server. Please check if server is not running.", Color.Red);
                return;
            }

            NetworkStream ntwStream = tcpClient.GetStream();
            if (ntwStream.CanWrite)
            {
                string ip = GetIP();
                if (ip == "-1")
                {
                    Console.WriteLine("Can't  receive IP. Please check network connection and try again.", Color.Red);
                    return;
                }
                Byte[] bytSend = Encoding.UTF8.GetBytes(ip);
                ntwStream.Write(bytSend, 0, bytSend.Length);
                WriteLog(ip);
            }
            else
                Console.WriteLine("Can't send IP to server. Is the server using the same version as client? Client is on: " + Assembly.GetEntryAssembly().GetName().Version, Color.Red);
            ntwStream.Close();
            tcpClient.Close();
        }


        static void CountDown(int time)
        {
            while (time > 0)
            {
                Console.SetCursorPosition(0, Console.CursorTop);
                Console.Write("                    ");
                Console.SetCursorPosition(0, Console.CursorTop);
                Console.Write("Next send in: " + time.ToString() + "s");                              //显示秒表计数
                Thread.Sleep(1000);         //等待1秒后再执行Timer()刷新计数
                time--;                                 //秒数减1
            }
            Console.SetCursorPosition(0, Console.CursorTop);
            Console.Write("                    ");
            Console.SetCursorPosition(0, Console.CursorTop);
            Console.Write("Sending...");
            Console.SetCursorPosition(0, Console.CursorTop);
        }

        static void Main(string[] args)
        {
            Console.Clear();
            Console.SetCursorPosition(0, 0);
            Console.WriteAscii("IP Upload C", Color.FromArgb(0, 255, 0));
            Console.WriteLine("By XiaoMingXD", Color.Yellow);
            //检查第二个参数是否有值 有则认为发送至参数指定的服务器 否则从配置文件读取服务器地址
            if (args.Length < 2)
            {
                //否则先检查是否有配置文件
                if (!File.Exists("config.ini"))
                    //如无则先创建配置文件
                    GetIPUser();
                //在读取配置文件读入全局
                GetIPFile();
            }
            else
            {
                //读取第一个参数作为IP存入全局
                IP = args[0];
                //利用ushort的0-65535检查 参数二 传入的端口是否正确
                try { Port = ushort.Parse(args[1]); }
                catch
                {
                    Console.WriteLine("WRONG PORT on argument 2. Should between 0-65535. Please try again.", Color.Red);
                    Environment.Exit(-1);
                }
            }
            Console.CursorVisible = false;
            Console.WriteLine("Client Started.", Color.FromArgb(0, 255, 0));
            Console.Write("IP: ", Color.FromArgb(0, 255, 0));
            Console.WriteLine(IP);
            Console.Write("Port: ", Color.FromArgb(0, 255, 0));
            Console.WriteLine(Port);
            Console.WriteLine();
            while (true)
            {
                SendIP();
                CountDown(600);//second
            }
        }
    }
}
